<template>
	<div id="communityBuildingList" v-cloak>
		<el-container>
			<el-aside width="200px">
				<el-tree :props="defaultProps" :load="loadChildrenNode" lazy :default-expanded-keys="default_expended_key" highlight-current node-key="id" ref="tree" :expand-on-click-node="false" accordion @node-click="handleNodeClick" @node-expand="handleNodeExpand">
				</el-tree>
			</el-aside>
			<el-main id="el-main">
				<buildingUnitList ref="buildingUnitList" v-show="unitVisible" @reload-treeNode="reloadCurrentTreeData"></buildingUnitList>
				<unitHouseList ref="unitHouseList" v-show="houseVisible"></unitHouseList>
				<div v-show="buildingVisible">
					<!--工具条-->
					<div name="searchColums" id="searchColums">
						<el-form :inline="true" :model="filters" size="small" ref="filters" class="searchForm">
							<el-form-item class="el-form-item" label="楼名称">
								<el-input v-model="filters.buildingName" name="buildingName" auto-complete="off" placeholder="请输入楼名称"></el-input>
							</el-form-item>
							<el-form-item class="el-form-item" label="楼类型">
								<el-select size="small" v-model="filters.buildingType" clearable placeholder="请选择">
									<el-option v-for="item in buildingTypeOptions" :key="item.value" :label="item.label" :value="item.value">
									</el-option>
								</el-select>
							</el-form-item>
							<el-form-item class="el-form-item" label="产权">
								<el-select size="small" v-model="filters.propertyRight" clearable placeholder="请选择">
									<el-option v-for="item in propertyRightOptions" :key="item.value" :label="item.label" :value="item.value">
									</el-option>
								</el-select>
							</el-form-item>

							<span class="bth_search">
								<el-form-item>
									<el-button type="success" icon="el-icon-search" v-on:click="getCommunityBuildings(true)">查询</el-button>
								</el-form-item>
								<el-form-item>
									<el-button icon="el-icon-refresh" @click="resetSearchForm('filters')">重置</el-button>
								</el-form-item>
							</span>
						</el-form>
					</div>
					<!--toolbar-->
					<el-row id="toolbar">
						<el-col :span="24">
							<div class="grid-content bg-purple-light">
								<el-button type="primary" size="mini" icon="el-icon-edit" :disabled="addDisabled" @click="handleAdd">新增</el-button>
								<el-button type="primary" size="mini" @click="batchRemove" :disabled="this.sels.length===0" icon="el-icon-delete">批量删除</el-button>
								<el-button type="primary" size="mini" @click="templeteDown" icon="el-icon-download">模板下载</el-button>
								<el-button type="primary" size="mini" @click="templeteUp" :disabled="uploadDisabled" icon="el-icon-upload">导入</el-button>
							</div>
						</el-col>
					</el-row>

					<!--列表-->
					<el-table :data="communityBuildings" id="datagrid" empty-text=" " height="410" border stripe size="mini" :header-row-class-name="headStyle" highlight-current-row v-loading="listLoading" :row-class-name="tableRowClassName" @sort-change="handleSortChange" @selection-change="selsChange" style="width: 100%;">
						<el-table-column type="selection" width="45"></el-table-column>
						<el-table-column prop="index" :formatter="index_formatter" label="序号" width="60"></el-table-column>
						<el-table-column prop="communityName" label="所属小区" width="120" show-overflow-tooltip></el-table-column>
						<el-table-column prop="buildingName" label="楼名称" width="120" show-overflow-tooltip></el-table-column>
						<el-table-column prop="buildingTypeName" label="楼类型" width="120" show-overflow-tooltip></el-table-column>
						<el-table-column prop="manager" label="负责人" width="120" show-overflow-tooltip></el-table-column>
						<el-table-column prop="size" label="面积" width="120" show-overflow-tooltip></el-table-column>
						<el-table-column prop="floorNumber" label="楼层数" width="120" show-overflow-tooltip></el-table-column>
						<el-table-column prop="position" label="楼位置" width="120" show-overflow-tooltip></el-table-column>
						<el-table-column prop="completeDate" label="竣工时间" width="120" show-overflow-tooltip></el-table-column>
						<el-table-column prop="developer" label="开发商" width="120" show-overflow-tooltip></el-table-column>
						<el-table-column prop="developerPhone" label="开发商电话" width="120" show-overflow-tooltip></el-table-column>
						<el-table-column prop="cleaningUser" label="保洁ID" width="120" show-overflow-tooltip></el-table-column>
						<el-table-column prop="propertyRightName" label="产权" width="120" show-overflow-tooltip></el-table-column>
						<el-table-column prop="houseNumber" label="户数" width="120" show-overflow-tooltip></el-table-column>
						<el-table-column prop="existUnit" label="是否存在单元" v-if="false"></el-table-column>
						<el-table-column prop="sort" label="排序" v-if="false"></el-table-column>
						<el-table-column label="操作" width="160" fixed="right">
							<template slot-scope="scope">
								<el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
								<el-button type="danger" size="mini" @click="handleDel(scope.$index, scope.row)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>

					<!--工具条-->
					<el-col :span="24" class="toolbar" id="pageDiv">
						<el-pagination small background :current-page="page" @current-change="handleCurrentChange" @size-change="handleSizeChange" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="total" layout="total,sizes, prev, pager, next" style="float:right;"></el-pagination>
					</el-col>

					<!--编辑界面-->
					<el-dialog title="编辑" :visible.sync="editFormVisible" :close-on-click-modal="false" @close="resetForm('editForm')">
						<el-form :model="editForm" label-width="80px" :rules="addFormRules" ref="editForm" size="mini">
							<el-col :span="12">
								<el-form-item label="楼名称" prop="buildingName">
									<el-input v-model="editForm.buildingName" auto-complete="off" placeholder="请输入楼名称"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="楼类型" prop="buildingType">
									<el-select size="small" v-model="editForm.buildingType" clearable placeholder="请选择">
										<el-option v-for="item in buildingTypeOptions" :key="item.value" :label="item.label" :value="item.value">
										</el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="负责人" prop="manager">
									<el-input v-model="editForm.manager" auto-complete="off" placeholder="请输入负责人"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="面积" prop="size">
									<el-input min="1" v-model.number="editForm.size" auto-complete="off" placeholder="请输入面积">
										<template slot="append">平方米</template>
									</el-input>
								</el-form-item>
							</el-col>

							<el-col :span="12">
								<el-form-item label="楼位置" prop="position">
									<el-input v-model="editForm.position" auto-complete="off" placeholder="请输入楼位置"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="竣工时间">
									<el-date-picker type="date" placeholder="选择竣工时间" v-model="editForm.completeDate"></el-date-picker>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="开发商" prop="developer">
									<el-input v-model="editForm.developer" auto-complete="off" placeholder="请输入开发商"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="序号" prop="sort">
									<el-input v-model.number="editForm.sort" auto-complete="off" placeholder="请输入"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="电话" prop="developerPhone">
									<el-input max="11" v-model="editForm.developerPhone" auto-complete="off" placeholder="请输入开发商电话"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="保洁ID" prop="cleaningUser">
									<el-input v-model.number="editForm.cleaningUser" auto-complete="off" placeholder="请输入保洁ID"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="楼层数" prop="floorNumber">
									<el-input v-model.number="editForm.floorNumber" auto-complete="off" placeholder="请输入楼层数">
										<template slot="append">层</template>
									</el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="单元" prop="existUnit">
									<el-select size="small" v-model="editForm.existUnit" clearable placeholder="请选择">
										<el-option v-for="item in buildingUnitOptions" :key="item.value" :label="item.label" :value="item.value">
										</el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="产权" prop="propertyRight">
									<el-select size="small" v-model="editForm.propertyRight" clearable placeholder="请选择">
										<el-option v-for="item in propertyRightOptions" :key="item.value" :label="item.label" :value="Number(item.value)">
										</el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="户数" prop="houseNumber">
									<el-input v-model.number="editForm.houseNumber" auto-complete="off" placeholder="请输入户数">
										<template slot="append">户</template>
									</el-input>
								</el-form-item>
							</el-col>

						</el-form>
						<div slot="footer" class="dialog-footer">
							<el-button @click.native="editFormVisible = false">取消</el-button>
							<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
							<!--<el-button type="primary" @click="resetForm('editForm')">重置</el-button>-->
						</div>
					</el-dialog>

					<!--新增界面-->
					<el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false" @close="resetForm('addForm')">
						<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm" size="mini">
							<el-input v-model="addForm.communityId" type="hidden" style="display: none!important;"></el-input>

							<el-col :span="12">
								<el-form-item label="楼名称" prop="buildingName">
									<el-input v-model="addForm.buildingName" auto-complete="off" placeholder="请输入楼名称"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="楼类型" prop="buildingType">
									<el-select size="small" v-model="addForm.buildingType" clearable placeholder="请选择">
										<el-option v-for="item in buildingTypeOptions" :key="item.value" :label="item.label" :value="item.value">
										</el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="负责人" prop="manager">
									<el-input v-model="addForm.manager" auto-complete="off" placeholder="请输入负责人"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="面积" prop="size">
									<el-input min="1" v-model.number="addForm.size" auto-complete="off" placeholder="请输入面积">
										<template slot="append">平方米</template>
									</el-input>
								</el-form-item>
							</el-col>

							<el-col :span="12">
								<el-form-item label="楼位置" prop="position">
									<el-input v-model="addForm.position" auto-complete="off" placeholder="请输入楼位置"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="竣工时间">
									<el-date-picker type="date" placeholder="选择竣工时间" v-model="addForm.completeDate"></el-date-picker>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="开发商" prop="developer">
									<el-input v-model="addForm.developer" auto-complete="off" placeholder="请输入开发商"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="序号" prop="sort">
									<el-input v-model.number="addForm.sort" auto-complete="off" placeholder="请输入"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="电话" prop="developerPhone">
									<el-input max="11" v-model="addForm.developerPhone" auto-complete="off" placeholder="请输入开发商电话"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="保洁ID" prop="cleaningUser">
									<el-input v-model.number="addForm.cleaningUser" auto-complete="off" placeholder="请输入保洁ID"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="楼层数" prop="floorNumber">
									<el-input v-model.number="addForm.floorNumber" auto-complete="off" placeholder="请输入楼层数">
										<template slot="append">层</template>
									</el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="单元" prop="existUnit">
									<el-select size="small" v-model="addForm.existUnit" clearable placeholder="请选择">
										<el-option v-for="item in buildingUnitOptions" :key="item.value" :label="item.label" :value="item.value">
										</el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="产权" prop="propertyRight">
									<el-select size="small" v-model="addForm.propertyRight" clearable placeholder="请选择">
										<el-option v-for="item in propertyRightOptions" :key="item.value" :label="item.label" :value="Number(item.value)">
										</el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="户数" prop="houseNumber">
									<el-input v-model.number="addForm.houseNumber" auto-complete="off" placeholder="请输入户数">
										<template slot="append">户</template>
									</el-input>
								</el-form-item>
							</el-col>

						</el-form>
						<div slot="footer" class="dialog-footer">
							<el-button @click.native="addFormVisible = false">取消</el-button>
							<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
							<el-button type="primary" @click="resetForm('addForm')">重置</el-button>
						</div>
					</el-dialog>
					<!--导入界面-->
					<el-dialog title="导入" :visible.sync="importFormVisible" :close-on-click-modal="false">
						<el-upload class="upload-demo" ref="upload" accept="xls,xlsx" action="admin/communityBuilding/upload" :on-preview="handlePreview" :on-remove="handleRemove" :on-success="handleSuccess" :before-upload="beforeAvatarUpload" :file-list="fileList" :headers="building_uploadHeader" :data="uploadParams" :auto-upload="false">
							<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
							<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload" :loading="addLoading">上传</el-button>
							<div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件</div>
						</el-upload>
					</el-dialog>
				</div>
			</el-main>
		</el-container>

	</div>
</template>
<script>
import { getToken, setToken, removeToken } from '@/util/auth'
import request from '@/router/axios'
import buildingUnitList from './buildingUnitList.vue'
import unitHouseList from './unitHouseList.vue'
var defaultNode = ''
export default {
  name: 'table_community_building',
  components: {
    buildingUnitList,
    unitHouseList
  },
  data() {
    return {
      filters: {
        buildingName: '',
        buildingType: '',
        propertyRight: ''
      },
      url: {
        list: '/admin/communityBuilding/page',
        del: '/admin/communityBuilding/doDel',
        batchDel: '/admin/communityBuilding/doBatchDel',
        save: '/admin/communityBuilding/doAdd',
        edit: '/admin/communityBuilding/doUpdate'
      },
      communityBuildings: [],
      houseVisible: false,
      unitVisible: false,
      buildingVisible: true,
      default_expended_key: [],
      fileList: [],
      total: 0,
      page: 1,
      pageSize: 10,
      sort: {
        sort: 'sort',
        order: 'asc'
      },
      listLoading: false,
      sels: [], // 列表选中列
      uploadParams: {},
      editFormVisible: false, // 编辑界面是否显示
      importFormVisible: false,
      editLoading: false,
      addFormVisible: false, // 新增界面是否显示
      addLoading: false,
      addDisabled: true,
      uploadDisabled: true,
      addFormRules: {
        buildingName: [
          {
            required: true,
            message: '请输入楼名称'
          }
        ],

        buildingType: [
          {
            required: true,
            message: '请选择楼类型'
          }
        ],
        developerPhone: [
          {
            pattern: /^1[3|4|5|7|8][0-9]\d{8}$/,
            message: '电话号码格式不正确'
          }
        ],
        houseNumber: [
          {
            type: 'number',
            message: '请输入数字'
          }
        ],
        size: [
          {
            type: 'number',
            message: '请输入数字'
          }
        ],
        floorNumber: [
          {
            type: 'number',
            message: '请输入数字'
          }
        ],
        //     cleaningUser: [{
        //       type: 'number',
        //       message: '请输入数字'
        // }],
        sort: [
          {
            type: 'number',
            message: '请输入数字'
          }
        ]
      },
      // 新增界面数据
      addForm: {
        developerPhone: '',
        houseNumber: '',
        size: '',
        sort: '',
        cleaningUser: '',
        floorNumber: ''
      },
      // 编辑界面数据
      editForm: {
        developerPhone: '',
        houseNumber: '',
        size: '',
        sort: '',
        cleaningUser: '',
        floorNumber: ''
      },
      formFile: {},
      buildingTreeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 数据字典
      // 产权
      propertyRightOptions: [],
      // 楼类型
      buildingTypeOptions: [],
      // 楼宇是否存在
      buildingUnitOptions: [],
      building_uploadHeader: {
        Authorization: 'Bearer ' + getToken()
      }
    }
  },
  methods: {
    handleSortChange(sort) {
      this.sort = {
        sort: sort.prop,
        order: sort.order == 'ascending' ? 'asc' : 'desc'
      }
      this.getCommunityBuildings()
    },

    handleDownFile(type, filePath) {
      var downUrl = this.url.downFile + '?down=' + type + '&dbPath=' + filePath
      window.open(downUrl)
    },
    tableRowClassName(row, index) {
      // 把每一行的索引放进row
      row.index = row.rowIndex
    },
    headStyle({ row, rowIndex }) {
      return 'table_head_style'
    },
    index_formatter: function(row, column, cellValue, index) {
      // 放回索引值
      return this.pageSize * (this.page - 1) + 1 + index
    },
    handleCurrentChange(val) {
      this.page = val
      this.getCommunityBuildings()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.page = 1
      this.getCommunityBuildings()
    },
    resetSearchForm(formName) {
      this.filters = {
        propertyRight: '',
        buildingName: '',
        buildingType: ''
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 获取用户列表
    getCommunityBuildings(flag) {
      // 获取当前树节点选中小区
      var communityId = this.$refs.tree.getCurrentKey()
      if (flag) {
        this.page = 1
      }
      const para = {
        params: {
          page: this.page,
          limit: this.pageSize,
          // 排序
          orderByField: this.sort.sort,
          isAsc: this.sort.order,
          communityId: communityId,
          buildingName: this.filters.buildingName,
          buildingType: this.filters.buildingType,
          propertyRight: this.filters.propertyRight
        }
      }
      this.listLoading = true
      request.get(this.url.list, para).then(res => {
        this.total = res.data.total
        var datas = res.data.records
        this.communityBuildings = datas
        this.listLoading = false
        this.reloadCurrentTreeData()
      })
    },
    // 删除
    handleDel: function(index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      })
        .then(() => {
          this.listLoading = true
          const para = {
            id: row.id
          }
          request
            .get(this.url.del, {
              params: para
            })
            .then(res => {
              this.listLoading = false
              this.$message({
                message: '删除成功',
                type: 'success',
                duration: 1500
              })
              this.getCommunityBuildings()
            })
        })
        .catch(() => {})
    },
    // 显示编辑界面
    handleEdit: function(index, row) {
      this.editFormVisible = true
      this.editForm = Object.assign({}, row)
      this.formFile = {}
    },
    // 显示新增界面
    handleAdd: function() {
      this.addFormVisible = true
      this.addForm = {
        existUnit: '1',
        communityId: this.$refs.tree.getCurrentKey()
      }
      this.formFile = {}
    },
    // 编辑
    editSubmit: function() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true
            const para = Object.assign({}, this.editForm)
            request.post(this.url.edit, para).then(res => {
              this.editLoading = false
              if (!res.data.data) {
                this.$message({
                  message: res.data.msg,
                  type: 'error',
                  duration: 1500
                })
                return
              }
              this.$message({
                message: '提交成功',
                type: 'success',
                duration: 1500
              })
              this.$refs['editForm'].resetFields()
              this.editFormVisible = false
              this.getCommunityBuildings()
            })
          })
        }
      })
    },
    // 新增
    addSubmit: function() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true
            const communityBuilding = Object.assign({}, this.addForm)
            request.post(this.url.save, communityBuilding).then(res => {
              this.addLoading = false
              if (!res.data.data) {
                this.$message({
                  message: res.data.msg,
                  type: 'error',
                  duration: 1500
                })
                return
              }

              this.$message({
                message: '提交成功',
                type: 'success',
                duration: 1500
              })
              this.$refs['addForm'].resetFields()
              this.addFormVisible = false
              this.getCommunityBuildings()
            })
          })
        }
      })
    },
    selsChange: function(sels) {
      this.sels = sels
    },

    // 模板下载
    templeteDown: function() {
      location.href = '/static/templates/building.xls'
    },
    // 模板上传
    templeteUp: function() {
      this.fileList = []
      this.uploadParams = {
        communityId: this.$refs.tree.getCurrentKey()
      }
      this.importFormVisible = true
    },
    submitUpload() {
      if (this.$refs.upload.uploadFiles.length == 0) {
        this.$message({
          message: '请先选择上传的文件。',
          type: 'info',
          duration: 2000
        })
        return
      }
      this.addLoading = true
      this.$refs.upload.submit()
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleSuccess(response, file, fileList) {
      this.addLoading = false
      if (!response.success) {
        this.$message.error(response.msg)
      } else {
        this.$message({
          message: response.msg,
          type: 'success',
          duration: 1500
        })
      }
      this.fileList = []
      this.importFormVisible = false
      // 刷新列表
      this.getCommunityBuildings()
    },
    beforeAvatarUpload(file) {
      const isXls = file.type === 'application/vnd.ms-excel'
      const isXlsx =
        file.type ===
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      if (!isXls && !isXlsx) {
        this.$message.error('格式不正确!')
      }

      return isXls || isXlsx
    },

    // 批量删除
    batchRemove: function() {
      var ids = this.sels.map(item => item.id).toString()
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          this.listLoading = true
          const para = {
            ids: ids
          }
          request
            .get(this.url.batchDel, {
              params: para
            })
            .then(res => {
              this.listLoading = false
              this.$message({
                message: '删除成功',
                type: 'success',
                duration: 1500
              })
              this.getCommunityBuildings()
            })
        })
        .catch(() => {})
    },

    // 初始化数据字典
    initDictsData: function() {
      request.get('/admin/dict/type/property_right').then(res => {
        if (res.status === 200) {
          this.propertyRightOptions = res.data
        }
      })
      request.get('/admin/dict/type/building_type').then(res => {
        if (res.status === 200) {
          this.buildingTypeOptions = res.data
        }
      })
      request.get('/admin/dict/type/building_unit').then(res => {
        if (res.status === 200) {
          this.buildingUnitOptions = res.data
        }
      })
    },

    reloadCurrentTreeData() {
      var data = this.$refs.tree.getCurrentNode()
      var node = this.$refs.tree.getNode(data.id)
      if (node.level === 0) {
        request.get('/admin/community?getCommunitysByCurrentUser').then(res => {
          if (res.status === 200) {
            this.$refs.tree.updateKeyChildren(node.key, res.data)
          }
        })
      } else if (node.level === 1) {
        // 点击小区节点，加载该小区下的楼宇信息
        request
          .get('/admin/communityBuilding/getCommunityBuildings/' + node.key)
          .then(res => {
            if (res.status === 200) {
              this.$refs.tree.updateKeyChildren(node.key, res.data)
            }
          })
      } else if (node.level === 2) {
        // 点击小区节点，加载该楼宇下的单元信息
        request
          .get('/admin/communityBuilding/getBuildingUnits/' + node.key)
          .then(res => {
            if (res.status === 200) {
              this.$refs.tree.updateKeyChildren(node.key, res.data)
            }
          })
      }
    },
    // 初始化树
    loadChildrenNode(node, resolve) {
      if (node.level === 0) {
        request.get('/admin/community?getCommunitysByCurrentUser').then(res => {
          if (res.status === 200) {
            defaultNode = res.data[0].id
            this.$refs.tree.setCurrentKey(defaultNode)
            return resolve(res.data)
          }
        })
      } else if (node.level === 1) {
        // 点击小区节点，加载该小区下的楼宇信息
        request
          .get('/admin/communityBuilding/getCommunityBuildings/' + node.key)
          .then(res => {
            if (res.status === 200) {
              return resolve(res.data)
            }
          })
      } else if (node.level === 2) {
        // 点击小区节点，加载该楼宇下的单元信息
        request
          .get('/admin/communityBuilding/getBuildingUnits/' + node.key)
          .then(res => {
            if (res.status === 200) {
              return resolve(res.data)
            }
          })
      } else {
        return resolve([])
      }
    },
    handleNodeExpand(data, node, e) {
      this.$refs.tree.setCurrentKey(data.id)
      this.handleNodeClick(data, node)
    },
    handleNodeClick(data, node) {
      this.addDisabled = false
      this.uploadDisabled = false
      var level = node.level
      if (level == 1) {
        this.buildingVisible = true
        this.houseVisible = false
        this.unitVisible = false
        this.$refs.buildingUnitList.communityId = data.id
        this.$refs.unitHouseList.communityId = data.id
        this.resetSearchForm()
        this.getCommunityBuildings(true)
      } else if (level == 2) {
        var existUnit = data.existUnit
        if (existUnit == '1') {
          // 楼宇存在单元
          this.buildingVisible = false
          this.houseVisible = false
          this.unitVisible = true
          this.$refs.unitHouseList.buildingId = data.id
          this.$refs.buildingUnitList.treeId = data.id
          this.$refs.buildingUnitList.getBuildingUnit(true)
          this.$refs.buildingUnitList.resetUnitForm()
          this.reloadCurrentTreeData()
        } else {
          this.buildingVisible = false
          this.houseVisible = true
          this.unitVisible = false
          this.$refs.unitHouseList.treeId = data.id
          this.$refs.unitHouseList.treeLevel = level
          this.$refs.unitHouseList.existUnit = existUnit
          this.$refs.unitHouseList.getUnitHouse(true)
          this.$refs.unitHouseList.resetHouseForm()
        }
      } else {
        this.buildingVisible = false
        this.houseVisible = true
        this.unitVisible = false
        this.$refs.unitHouseList.treeId = data.id
        this.$refs.unitHouseList.treeLevel = level
        this.$refs.unitHouseList.existUnit = data.existUnit
        this.$refs.unitHouseList.getUnitHouse(true)
        this.$refs.unitHouseList.resetHouseForm()
      }
    }
    // 树相关方法结束
  },
  mounted() {
    // 加载楼房树
    this.initDictsData()
  }
}
</script>
